package com.wn.class30.HandlerException;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;


/**
* @author 周豪 E-mail: 
* @version 创建时间：2020年3月8日 下午7:39:03 
* 类说明:全局异常
*/

@ControllerAdvice
public class GlobalExceptionHandler {
	/*参数验证异常*/
	@ExceptionHandler(ConstraintViolationException.class)
	public ModelAndView constraintViolationException(HttpServletRequest request, Throwable ex) {
		String message = ex.getMessage();
		ModelAndView modelAndView=getModelAndView(message);
		return modelAndView;
	}

	/*shiro认证异常*/
	@ExceptionHandler(UnknownAccountException.class)
	public ModelAndView authenticationException(HttpServletRequest request, Throwable ex) {
		ex.printStackTrace();
		return getModelAndView("no user");
	}
	/*shiro权限不足异常*/
	@ExceptionHandler(UnauthorizedException.class)
	public ModelAndView UnauthorizedException(HttpServletRequest request, Throwable ex) {
		ex.printStackTrace();
		return getModelAndView("premissionException");
	}


	/*shiro账号密码不匹配*/
	@ExceptionHandler(IncorrectCredentialsException.class)
	public ModelAndView incorrectCredentialsException(HttpServletRequest request, Throwable ex) {
		ex.printStackTrace();
		return getModelAndView("password not map");
	}
	/*shiro全局异常*/
	@ExceptionHandler(Exception.class)
	public ModelAndView exceptionHandler(HttpServletRequest request, Throwable ex) {
		ex.printStackTrace();
		return getModelAndView("serverException");
	}

	@ExceptionHandler(ReloginException.class)
	public ModelAndView reloginException(Throwable ex){
		ex.printStackTrace();
		return getModelAndView("relogin");
	}

	/*获取ModelAndView*/
	public ModelAndView getModelAndView(String message) {
		ModelAndView modelAndView = new ModelAndView();
		  FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();
		  HashMap<String, String> hashMap = new HashMap();
                      hashMap.put("code", "500");
                      hashMap.put("message", message);
	            fastJsonJsonView.setAttributesMap(hashMap);
	            modelAndView.setView(fastJsonJsonView);
	            return modelAndView;
	}
	
}
